package com.weilele.leisure.time.ui.module.video_cache

import android.os.Bundle
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import com.google.android.exoplayer2.offline.Download
import com.google.android.exoplayer2.offline.DownloadManager
import com.weilele.base.library.BaseBindingFragment
import com.weilele.base.library.FragmentContainerActivity
import com.weilele.base.library.SwitchView
import com.weilele.leisure.time.R
import com.weilele.leisure.time.bean.db.HistoryVideoBean
import com.weilele.leisure.time.databinding.FragmentVideoCacheDetailBinding
import com.weilele.leisure.time.ui.holder.CacheDetailHolder
import com.weilele.leisure.time.ui.module.video_detail.VideoDetailFragment
import com.weilele.mvvm.adapter.refreshList
import com.weilele.mvvm.base.livedata.appCompatActivity
import com.weilele.mvvm.utils.formJsonString
import com.weilele.mvvm.utils.safeGet
import com.weilele.mvvm.utils.toJsonString
import com.weilele.mvvm.view.SimpleSwitchView
import com.yizisu.playerlibrary.service.download.PlayerDownload
import java.lang.Exception


class VideoCacheDetailFragment : BaseBindingFragment<FragmentVideoCacheDetailBinding>() {
    companion object {
        private const val KEY_VIDEO_ID = "KEY_VIDEO_ID"
        fun start(appCompatActivity: AppCompatActivity?, videoInfo: HistoryVideoBean?) {
            appCompatActivity ?: return
            FragmentContainerActivity.start<VideoCacheDetailFragment>(
                appCompatActivity,
                bundle = Bundle().apply {
                    putString(KEY_VIDEO_ID, videoInfo?.toJsonString())
                })
        }
    }

    private val videoInfo by lazy {
        arguments?.getString(KEY_VIDEO_ID)?.formJsonString<HistoryVideoBean>()
    }

    private val rcvAdapter = CacheDetailHolder.toAdapter().apply {
        setOnHolderClickListener(R.id.tvDelete) { holder, clickView ->
            deleteVideo(holder.safeGet())
        }
    }


    override fun initUi(savedInstanceState: Bundle?) {
        super.initUi(savedInstanceState)
        setTitle(videoInfo?.title ?: "下载详情")
        PlayerDownload.addNotificationListener(listener)
        mBinding.rcv.adapter = rcvAdapter
        enableSwipeDelete()
        rcvAdapter.refreshList(getCacheList())
    }

    override fun onDestroyView() {
        PlayerDownload.removeNotificationListener(listener)
        super.onDestroyView()
    }

    private val listener = object : PlayerDownload.NotificationListener {
        override fun updateNotification(downloads: MutableList<Download>) {
            rcvAdapter.currentList.forEachIndexed { index, download ->
                downloads.forEach {
                    if (it.request.id == download.request.id) {
                        mBinding.rcv.findViewHolderForAdapterPosition(index)
                            .safeGet<CacheDetailHolder>()?.updateProgress(it)
                        rcvAdapter.updateItem(index,it,null,false)
                    }
                }
            }
        }

        override fun onDownloadChanged(
            downloadManager: DownloadManager,
            download: Download,
            finalException: Exception?
        ) {
            super.onDownloadChanged(downloadManager, download, finalException)
            rcvAdapter.currentList.forEachIndexed { index, down ->
                if (down.request.id == download.request.id) {
                    mBinding.rcv.findViewHolderForAdapterPosition(index)
                        .safeGet<CacheDetailHolder>()?.updateProgress(download)
                    rcvAdapter.updateItem(index,download,null,false)
                }
            }
        }
    }
    private val videoDetailTitle = "视频详情页"
    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        super.onCreateOptionsMenu(menu, inflater)
        menu.add(videoDetailTitle).also {
            it.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS)
        }
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.title == videoDetailTitle) {
            VideoDetailFragment.start(this, videoInfo)
            appCompatActivity?.finish()
        }
        return super.onOptionsItemSelected(item)
    }


    /**
     * 根据id筛选缓存列表
     */
    private fun getCacheList(): MutableList<Download> {
        return VideoCacheFragment.getDownloadByVideoId(
            videoInfo?.videoId,
            PlayerDownload.getAllDownloads()
        )
    }

    private fun enableSwipeDelete() {
        ItemTouchHelper(object : ItemTouchHelper.SimpleCallback(
            0,
            ItemTouchHelper.LEFT
                    or ItemTouchHelper.RIGHT
        ) {
            override fun onMove(
                recyclerView: RecyclerView,
                viewHolder: RecyclerView.ViewHolder,
                target: RecyclerView.ViewHolder
            ): Boolean {
                return true
            }

            override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
                deleteVideo(viewHolder.safeGet<CacheDetailHolder>())
            }
        }).apply {
            this.attachToRecyclerView(mBinding.rcv)
        }
    }

    private fun deleteVideo(holder: CacheDetailHolder?) {
        holder ?: return
        val index = holder.bindingPosition
        val data = rcvAdapter.getItemData(index)?:return
        rcvAdapter.removeItem(index)
        PlayerDownload.removeDownload(data.request.id)
        if (rcvAdapter.currentList.isNullOrEmpty()) {
            showOtherView(
                SwitchView.OtherBean(
                    getString(R.string.no_cache_hint),
                    R.drawable.icon_empty
                )
            )
        }
    }

    override fun isNeedSwitchView(): Boolean {
        return true
    }

    override fun isNeedToolbar(): Boolean {
        return true
    }
}